package com.reformer.commons.json;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.sql.Timestamp;

public class GsonTimestampAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp> {
    private static GsonTimestampAdapter instance = new GsonTimestampAdapter();

    public GsonTimestampAdapter() {
    }

    public static GsonTimestampAdapter getInstance() {
        return instance;
    }

    @Override
    public Timestamp deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
        if (json != null) {
            try {
                return new Timestamp(json.getAsLong());
            } catch (JsonParseException e) {
                throw e;
            }
        }
        return null;
    }

    @Override
    public JsonElement serialize(Timestamp value, Type type, JsonSerializationContext context) {
        if (value != null) {
            return new JsonPrimitive(value.getTime());
        }
        return null;
    }

}
